$(document).ready(function(){
	setDialog();
	closeDialog();
	$("#userRoleNames").hide();
	$("#userMore").hide();
	//初始化表格
	$('#dataGridTable').datagrid({
		columns:[[ 
		   {field:'workNumber',title:'工号',width:70,align:'center'},
           {field:'userName',title:'用户名',width:120,align:'center'}, 
           {field:'realName',title:'真实姓名',width:70,align:'center'},
           {field:'accountCount',title:'状态',width:50,align:'center',formatter:updateStates},
           {field:'mobileNum',title:'手机号码',width:90,align:'center'},
           {field:'userEmail',title:'电子邮箱',width:130,align:'center'},
           {field:'userCount',title:'登录次数',width:60,align:'center'},
           {field:'createUser',title:'记录建立者',width:createUserWidth,align:'center'},
           {field:'createTime',title:'记录建立时间',width:createTimeWidth,align:'center'},
         ]]
 	});
	$('#userName').textbox('textbox').keydown(function (e) {
	   if (e.keyCode == 13) {
		   $('#userName').textbox('setValue', $(this).val());
			resetDialogTo();
			userInfos();
		    queryUser();
	    }
	});
	$('#realName').textbox('textbox').keydown(function (e) {
		if (e.keyCode == 13) {
			$('#realName').textbox('setValue', $(this).val());
			resetDialogTo();
			userInfos();
			queryUser();
		}
	});
	$('#workNumber').textbox('textbox').keydown(function (e) {
		if (e.keyCode == 13) {
			$('#workNumber').textbox('setValue', $(this).val());
			resetDialogTo();
			userInfos();
			queryUser();
			
		}
	});
});

//保存
function saveUser(){
	
	var userIdInfo=$("#userIdInfo").val();
	var userNameInfo=$("#userNameInfo").val();
	var realNameInfo=$("#realNameInfo").val();
	var userGenderInfo=$("#userGenderInfo").combobox('getValue');
	var birthDayInfo=$("#birthDayInfo").datebox('getValue');
	var mobileNumInfo=$("#mobileNumInfo").val();
	var phoneNumInfo=$("#phoneNumInfo").val();
	var userEmailInfo=$("#userEmailInfo").val();
	var qqNumInfo=$("#qqNumInfo").val();
	var workNumberInfo=$("#workNumberInfo").val();
	var userAddressInfo=$("#userAddressInfo").val();
	var user_departmentId = $('#user_departmentId').combotree('getValue');
	var user_departmentName = $('#user_departmentId').combotree('getText');
	var accountCount = $("#accountCount").val();
	var gridRole = $('#roleIds').combogrid('grid');
	var checkedProDatas = gridRole.datagrid('getChecked');
	var checkedProDataStr = "";
	for(var i = 0; i <  checkedProDatas.length ; i++){
		if(i==0){
			checkedProDataStr += checkedProDatas[i].rolesId;
		} else {
			checkedProDataStr += "#"+checkedProDatas[i].rolesId;
		}
	}	
	if(workNumberInfo==null||workNumberInfo==''){
		sysMsgShow("工号不允许为空!");
		return false;
	}else if(userNameInfo==null||userNameInfo==''){
		sysMsgShow("用户名不允许为空!");
		return false;
	
	}else if(realNameInfo==null||realNameInfo==''){
		sysMsgShow("真实姓名不允许为空!");
		return false;
	}else if(userGenderInfo==null||userGenderInfo==''){
		sysMsgShow("性别不允许为空!");
		return false;
	
	}else if(mobileNumInfo==null||mobileNumInfo==''){
		sysMsgShow("手机号码不允许为空!");
		return false;
	
	}else if(!isMobileNum(mobileNumInfo)){
		sysMsgShow("手机号码不正确!");
		return false;
		
	}else if(userEmailInfo==null||userEmailInfo==''){
		sysMsgShow("邮箱不允许为空!");
		return false;
	}else if(!isEmail(userEmailInfo)){
		sysMsgShow("邮箱不正确!");
		return false;
	}else if(user_departmentId==null||user_departmentId==''){
		sysMsgShow("组织架构不允许为空!");
		return false;
	}else{

		$.ajax({
			async : false,
			cache:false,
			type: 'post',
			dataType : "json",
			data : {
				"user.userId" : userIdInfo,
				"user.userName" : userNameInfo,
				"user.realName" : realNameInfo,
				"user.userGender" : userGenderInfo,
				"user.birthDay" : birthDayInfo,
				"user.mobileNum" : mobileNumInfo,
				"user.phoneNum" : phoneNumInfo,
				"user.userEmail" : userEmailInfo,
				"user.qqNum" : qqNumInfo,
				"user.workNumber" : workNumberInfo,
				"user.userAddress" : userAddressInfo,
				"user.manageRole" : checkedProDataStr,
				"user.departmentId" : user_departmentId,
				"user.departmentName" : user_departmentName,
				"user.accountCount" : accountCount
			},
			url: 'sys/saveUser.action',
			error: function () {
				sysErrorShow('请求失败!');
			},success:function(data){
				var messgage = userIdInfo?"修改成功!":"添加成功!";
				if(data.success==true){
					reloadTable();
					closeDialog();
					resetDialogTo();
					userInfos();
				}else{
					messgage = data.msg;
				}
				sysMsgShow(messgage);
			}
		});
	
	}	
}

//删除
function delPortal(){
	if($('#dataGridTable').datagrid('getSelected')){
		var ids = [];
		var cods = [];
		var selectedRow = $('#dataGridTable').datagrid('getSelections');
		for(var i=0;i<selectedRow.length;i++){
			ids.push(selectedRow[i].userId);
			cods.push(selectedRow[i].userName);
		}
		var userId = ids.join(',');
		$.messager.confirm('删除提示', '你确定删除下列用户吗?<br/><br/>'+cods.join(','), function(r){
				if (r){
					var url = 'sys/deleteUser.action?user.userId='+userId;
					$.ajax({
						async : false,
						cache:false,
						type: 'post',
						dataType : "json",
						url:url,
						error: function () {
							sysErrorShow('请求失败');
						},success:function(data){
							if(data.success==true){
								sysMsgShow("删除成功!");
								resetDialogTo();
								userInfos();
							}else{
								sysErrorShow(data.msg);
							}
							reloadTable();
							
						
						}
					});
				}
		});
	}
	else
	{
		noSelectData();
	}
}

//查询
function queryUser(){
	resetDialogTo();
	userInfos();
	$("#dataGridTable").datagrid('reload',{
		'user.workNumber' : $("#workNumber").val(),
	 	'user.userName' : $("#userName").val(),
	 	'user.realName' : $("#realName").val(),
	 	'user.workNumber' : $("#workNumber").val()
	}); 
}

/**--------------操作弹出框------------------**/
//初始化模窗
function setDialog(){
	$('#portalInfoDialog').dialog({
		modal: true,
		collapsible : true,
		resizable : true,
		onClose : function(){
			resetDialog();
		}
	});
}

//打开添加或修改模窗
function openDialog_addPortal(did,rid){
		loadUserRoles(did,rid);
	$('#portalInfoDialog').dialog({
		closed: false,
		modal:true,
        title: "新增用户",
        buttons: [{
            text: '确定',
            iconCls: 'icon-ok',
            handler: saveUser
        }, {
            text: '取消',
            iconCls: 'icon-cancel',
            handler: function () {
                $('#portalInfoDialog').dialog('close');                    
            }
        }]
    });
}

//打开编辑模窗
function openDialog_editPortal(){
	if($('#dataGridTable').datagrid('getSelected')){
		var userId = $('#dataGridTable').datagrid('getSelections')[0].userId;
		$.getJSON("sys/findUserById.action?user.userId="+userId,null,
		function msg(json){
			$("#userIdInfo").val(userId);
			$("#userNameInfo").textbox('setValue',json.object.userName);
			$("#realNameInfo").textbox('setValue',json.object.realName);
			$("#userGenderInfo").combobox('setValue',json.object.userGender);
			$("#birthDayInfo").datebox('setValue',json.object.birthDay);
			$("#mobileNumInfo").textbox('setValue',json.object.mobileNum);
			$("#phoneNumInfo").textbox('setValue',json.object.phoneNum);
			$("#userEmailInfo").textbox('setValue',json.object.userEmail);
			$("#qqNumInfo").textbox('setValue',json.object.qqNum);
			$("#workNumberInfo").textbox('setValue',json.object.workNumber);
			$("#userAddressInfo").textbox('setValue',json.object.userAddress);
			$("#accountCount").val(json.object.accountCount);
			openDialog_addPortal(json.object.departmentId,json.object.manageRoleArray);
			$('#portalInfoDialog').dialog('setTitle','编辑用户'); 
		});
	}
	else
	{
		noSelectData();
	}
}

//关闭模窗
function closeDialog(){
	$('#portalInfoDialog').dialog('close');
}

//清空控件值
function resetDialog(){
	$("#userIdInfo").val('');
	$("#accountCount").val('');
	$("#userNameInfo").textbox('setValue','');
	$("#realNameInfo").textbox('setValue','');
	$("#birthDayInfo").datebox('setValue','');
	$("#mobileNumInfo").textbox('setValue','');
	$("#userEmailInfo").textbox('setValue','');
	$("#qqNumInfo").textbox('setValue','');
	$("#workNumberInfo").textbox('setValue','');
	$("#userAddressInfo").textbox('setValue','');
	$("#phoneNumInfo").textbox('setValue','');
	$("#userGenderInfo").combobox('setValue','0');
	$('#user_departmentId').combotree('setValue','');
	$('#roleIds').combogrid('setValue','');
}

//清空右侧列表
function resetDialogTo(){
	$("#u_roles").html("&nbsp;");
	$("#u_workNumber").html("&nbsp;");
	$("#u_userGender").html("&nbsp;");
	$("#u_birthDay").html("&nbsp;");
	$("#u_userEmail").html("&nbsp;");
	$("#u_phoneNum").html("&nbsp;");
	$("#u_qqNum").html("&nbsp;");
	$("#u_userAddress").html("&nbsp;");
	$("#u_userCount").html("&nbsp;");
	$("#u_lastLoginTime").html("&nbsp;");
	$("#u_createUser").html("&nbsp;");
	$("#u_createTime").html("&nbsp;");
	$("#u_lastModifiedUser").html("&nbsp;");
	$("#u_lastModifiedTime").html("&nbsp;");
	$("#u_userName").html("&nbsp;");
	$("#u_realName").html("&nbsp;");
	$("#u_mobileNum").html("&nbsp;");
	$('#u_departmentId').html("&nbsp;");
}

//刷新表格
function reloadTable(){
	$('#dataGridTable').datagrid('reload');
}

//刷新
function reloads()
{
	$("#userName").textbox('setValue','');
	$("#realName").textbox('setValue','');
	$("#workNumber").textbox('setValue','');
	queryUser();
	resetDialogTo();
	userInfos();
}

function loadUserRoles(depId,roleId){
	var dId = $('#userRolesIds').val();
	if('0' == dId){
		window.bgidx = {treeNotLeafSelected:true};
		$('#user_departmentId').combotree({    
			url: 'sys/queryDepartment.action',   
			valueField:'departmentId',
			textField:'departmentName',
			loadFilter: function(data){   
				return data.rows;   
			}
		
		});
		
	$('#roleIds').combogrid({    
	    panelWidth:430,
	    rownumbers:true,
	    pagination:true,
  		editable:false,
  		toolbar:'toolbar2',
  		multiple:true,
  		url:'sys/findRole.action',
	    idField:'rolesId',    
	    textField:'rolesName',    
	    columns:[[    
            	{field:'rolesId',title:'角色名称',width:150,hidden:'true',align:'center'},  
                {field:'rolesName',title:'角色名称',width:150,align:'center'},    
                {field:'createUser',title:'记录建立者',width:createUserWidth,align:'center'},    
                {field:'createTime',title:'记录建立时间',width:createTimeWidth,align:'center'}   
                ]],
                onLoadSuccess:function(){
                	$('#userRolesIds').val("1");
                	if(depId != undefined){
                		$('#user_departmentId').combotree('setValue',depId);
                		$('#roleIds').combogrid('setValues',roleId);
                		}
                	
                }
		});  
		
	}else{
		if(depId != undefined){
		$('#user_departmentId').combotree('setValue',depId);
		$('#roleIds').combogrid('setValues',roleId);
		} else {
			return;
		}
	}

}

//改变状态
function enable(){
	var selectedData = $('#dataGridTable').datagrid('getSelections');
	if(selectedData.length > 0){
		var data = selectedData[0];
		var userId = data.userId;
		var accountCount = data.accountCount;
		$.ajax({
			async : false,
			cache:false,
			type: 'POST',
			dataType : "json",
			data : {
				"user.userId" : userId,
				"user.accountCount" :accountCount
			},
			url: 'sys/updateUserStatus.action',//请求的action路径
			error: function () {//请求失败处理函数
				sysErrorShow('请求失败!');
			},success:function(data){
				if(data.success==true){//未返回任何消息表示添加成功
					sysMsgShow('操作成功!');
					queryUser();
				}else{//返回异常信息
					if(data.msg='101')
					{
						sysMsgShow('修改状态失败!');
					}
				}
			}
		});
	} else {
		noSelectData();
	}
}
function updateStates(value,row){
	var accountCount = row.accountCount;
	if(accountCount=='1'){
		accountCount="<image src='../../resources/images/icons/yes.png'/>";
	}else if(accountCount=='0'){
		accountCount="<image src='../../resources/images/icons/stop.png'/>";
	}else{
		accountCount='';
	}
	return accountCount;
};
//禁用启用监听
function doEvent(rowIndex, rowData){
	var disableBtnFlag = false;
	var enableBtnFlag = false;
	//获得name值
	for(var i=0;i<resource.length;i++){
		var disableBtnName = $('#disableBtn').attr("name");
		if(resource[i].trim()==disableBtnName.trim())
		{
			disableBtnFlag = true;
		}
		if(resource[i].trim()==$('#enableBtn').attr("name"))
		{
			enableBtnFlag = true;
		}
	}
	if(1==rowData.accountCount && !disableBtnFlag){
		$('#disableBtn').linkbutton("enable");
		$('#enableBtn').linkbutton("disable");
	}else{
		$('#disableBtn').linkbutton("disable");
	}
	if(0==rowData.accountCount && !enableBtnFlag){
		$('#enableBtn').linkbutton("enable");
		$('#disableBtn').linkbutton("disable");
	}else{
		$('#enableBtn').linkbutton("disable");
	}
}

function userFrameMod(){
	var v = $('#userRolesIds').val();
	if("1" == v){
		$('#userRolesIds').val("1");
	}else{
		$('#userRolesIds').val("0");
	}
	if($('#dataGridTable').datagrid('getSelected')){
		var userId = $('#dataGridTable').datagrid('getSelections')[0].userId;
		$.ajax({
			async : false,
			cache:false,
			type: 'POST',
			dataType : "json",
			url: 'sys/findUser.action',//请求的action路径
			data : {
				"user.userId":userId
			},
			success:function(data,action,opt){
				if("" == data.object){
					$("#u_roles").html("&nbsp;");
				}else{
					var str = data.object;
					$("#u_roles").html(str.replace(/,/g,"<br/>"));
				}
				if(data.rows[0].workNumber != null){
					$("#u_workNumber").text(data.rows[0].workNumber);
				}else{
					$("#u_workNumber").html("&nbsp;");
				}
				if(data.rows[0].userGender != null){
					
					if('0' == data.rows[0].userGender){
						$("#u_userGender").text("未知");
					} else if('1' == data.rows[0].userGender){
						$("#u_userGender").text("女");
					} else{
						$("#u_userGender").text("男");
					}
				}else{
					$("#u_userGender").html("&nbsp;");
				}
				if(data.rows[0].birthDay != null){
					$("#u_birthDay").text(data.rows[0].birthDay);
				}else{
					$("#u_birthDay").html("&nbsp;");
				}
				if(data.rows[0].userEmail != null){
					$("#u_userEmail").text(data.rows[0].userEmail);
				}else{
					$("#u_userEmail").html("&nbsp;");
				}
				if(data.rows[0].phoneNum != null){
					$("#u_phoneNum").text(data.rows[0].phoneNum);
				}else{
					$("#u_phoneNum").html("&nbsp;");
				}
				if(data.rows[0].qqNum != null){
					$("#u_qqNum").text(data.rows[0].qqNum);
				}else{
					$("#u_qqNum").html("&nbsp;");
				}
				if(data.rows[0].userAddress != null){
					$("#u_userAddress").text(data.rows[0].userAddress);
				}else{
					$("#u_userAddress").html("&nbsp;");
				}
				if(data.rows[0].userCount != null){
					$("#u_userCount").text(data.rows[0].userCount);
				}else{
					$("#u_userCount").html("&nbsp;");
				}
				if(data.rows[0].lastLoginTime != null){
					$("#u_lastLoginTime").text(data.rows[0].lastLoginTime);
				}else{
					$("#u_lastLoginTime").html("&nbsp;");
				}
				if(data.rows[0].createTime != null){
					$("#u_createTime").text(data.rows[0].createTime);
				}else{
					$("#u_createTime").html("&nbsp;");
				}
				if(data.rows[0].lastModifiedUser != null){
					$("#u_lastModifiedUser").text(data.rows[0].lastModifiedUser);
				}else{
					$("#u_lastModifiedUser").html("&nbsp;");
				}
				if(data.rows[0].lastModifiedTime != null){
					$("#u_lastModifiedTime").text(data.rows[0].lastModifiedTime);
				}else{
					$("#u_lastModifiedTime").html("&nbsp;");
				}
				if(data.rows[0].userName != null){
					$("#u_userName").text(data.rows[0].userName);
				}else{
					$("#u_userName").html("&nbsp;");
				}
				if(data.rows[0].realName != null){
					$("#u_realName").text(data.rows[0].realName);
				}else{
					$("#u_realName").html("&nbsp;");
				}
				if(data.rows[0].mobileNum != null){
					$("#u_mobileNum").text(data.rows[0].mobileNum);
				}else{
					$("#u_mobileNum").html("&nbsp;");
				}
				if(data.rows[0].createUser != null){
					$("#u_createUser").text(data.rows[0].createUser);
				}else{
					$("#u_createUser").html("&nbsp;");
				}
				if(data.rows[0].departmentId != null){
					$.ajax({
						async : false,
						cache:false,
						type: 'POST',
						dataType : "json",
						url: 'sys/queryDepartmentById.action',//请求的action路径
						data : {
							"department.departmentId" : data.rows[0].departmentId
						},
						success:function(datas,actions,opts){
							$("#u_departmentId").text(datas.object);
						}
					});	
					
				}else{
					$("#u_departmentId").html("&nbsp;");
				}
				
	
			}
		});
	} else {
		noSelectData();
	}
}
function userInfos(){
	$("#userInfos").show();
	$("#userRoleNames").hide();
	$("#userMore").hide();
}
function userRoleNames(){
	$("#userRoleNames").show();
	$("#userInfos").hide();
	$("#userMore").hide();
}
function userMore(){
	$("#userMore").show();
	$("#userRoleNames").hide();
	$("#userInfos").hide();
}
//判断手机
function isMobileNum(str) {
	var re = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
	return re.test(str);
}
//判断邮箱
function isEmail(str) {
	var re = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
	return re.test(str);
}

//状态转换
function areaSatuts(value,row,index){
	var text='';
	if(value=='0'){
		text='<image src="resources/images/icons/stop.png"/>';
	}
	else if(value=='1'){
		text='<image src="resources/images/icons/yes.png"/>';
	}
	return text;
}